/**
 *******************************************************************************
 * @FileName  : tlsr825x_iic.c
 * @Author    : GaoQiu
 * @CreateDate: 2020-09-10
 * @Copyright : Copyright(C) GaoQiu
 *              All Rights Reserved.
 *
 *******************************************************************************
 *
 * The information contained herein is confidential and proprietary property of
 * GaoQiu and is available under the terms of Commercial License Agreement
 * between GaoQiu and the licensee in separate contract or the terms described
 * here-in.
 *
 * This heading MUST NOT be removed from this file.
 *
 * Licensees are granted free, non-transferable use of the information in this
 * file under Mutual Non-Disclosure Agreement. NO WARRENTY of ANY KIND is provided.
 *
 *******************************************************************************
 */
#include "tlsr825x_iic.h"
#include "tlsr825x_systimer.h"

typedef struct{
	uint8_t   cfgValid;
	uint16_t  slvAddr;
	uint32_t  sysCllk;
	uint32_t  i2cClk;
	uint32_t  timeout; /*!< unit: us*/
}I2cCb_t;

static I2cCb_t I2cCb;

void I2C_MstInit(uint32_t i2cClkHz, uint8_t slvAddr, uint32_t sysClkHz)
{
	I2cCb.slvAddr  = slvAddr;
	I2cCb.sysCllk  = sysClkHz;
	I2cCb.i2cClk   = i2cClkHz;
	I2cCb.timeout  = 1000;
	I2cCb.cfgValid = true;

	I2C->I2C_CLK    = sysClkHz/(i2cClkHz << 2);
	I2C->I2C_ID     = slvAddr & 0xff;
	I2C->I2C_CTRL0 |= I2C_CTRL0_MST_EN;
	SPI->CLK &= ~(1<<7);
}

int I2C_WriteByte(uint8_t cmd, uint8_t value)
{
	if(I2cCb.cfgValid == false){
		return -1;
	}

	I2C->I2C_ID &= ~(1<<0); // bit0==0: write; bit0==1:read
	I2C->I2C_ADDR  = cmd;
	I2C->I2C_CTRL1 = I2C_CTRL1_TX_START|I2C_CTRL1_TX_ID|I2C_CTRL1_HI_ADDR;
	while(I2C->I2C_STA & I2C_STA_MST_BUSY);

	/* send data */
	I2C->I2C_DR = value;
	I2C->I2C_CTRL1 = I2C_CTRL1_RD_DAT;
	while(I2C->I2C_STA & I2C_STA_MST_BUSY);

	/* send stop */
	I2C->I2C_CTRL1 = I2C_CTRL1_TX_STOP;
	while(I2C->I2C_STA & I2C_STA_MST_BUSY);

	return 0;
}

int I2C_Write(uint8_t cmd, uint8_t *pData, uint32_t len)
{
	if(I2cCb.cfgValid == false){
		return -1;
	}

	//uint32_t txTick = 0;

	I2C->I2C_ID &= ~(1<<0); // bit0==0: write; bit0==1:read
	I2C->I2C_ADDR  = cmd;
	I2C->I2C_CTRL1 = I2C_CTRL1_TX_START|I2C_CTRL1_TX_ID|I2C_CTRL1_HI_ADDR;
	while(I2C->I2C_STA & I2C_STA_MST_BUSY);

	/* send data */
	for(int i=0; i<len; i++)
	{
		I2C->I2C_DR = pData[i];
		I2C->I2C_CTRL1 = I2C_CTRL1_RD_DAT;
		while(I2C->I2C_STA & I2C_STA_MST_BUSY);
	}

	/* send stop */
	I2C->I2C_CTRL1 = I2C_CTRL1_TX_STOP;
	while(I2C->I2C_STA & I2C_STA_MST_BUSY);

	return 0;
}

